import qs from 'qs';
import axios from 'axios';

const BASE_URL = 'https://api.huhuiyu.top';
const TOKEN_KEY = BASE_URL + '_token';

// 本地保存token的部分
const LocalToken = {
  save: (data) => {
    if (data && data.token) {
      localStorage.setItem(TOKEN_KEY, data.token);
    }
  },
  load: () => {
    let token = localStorage.getItem(TOKEN_KEY);
    return token ? token : '';
  },
  remove: () => {
    localStorage.removeItem(TOKEN_KEY);
  },
};

const Api = {
  upload: (url, file, param, cb) => {
    let formData = new FormData();
    // 文件参数
    formData.append('file', file);
    // 其它数据
    if (param) {
      for (let key in param) {
        formData.append(key, param[key]);
      }
    }
    let promise = axios({
      url: BASE_URL + url,
      data: formData,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: LocalToken.load(),
      },
    });
    // 处理结果
    promise
      .then((resp) => {
        LocalToken.save(resp.data);
        cb(resp.data);
      })
      .catch((err) => {
        console.error(err);
        cb({
          code: 500,
          message: '网站忙，请稍后重试',
          success: false,
        });
      });
      
  },
  getUserLogo: (uid) => {
    return `${BASE_URL}/user/logo/${uid}?request_token=${LocalToken.load()}`;
  },
  ajax: (url, param, cb, method) => {
    // get方法需要单独处理，参数要通过地址栏传递
    if (method === 'get') {
      url += '?' + qs.stringify(param, { allowDots: true });
      param = '';
    }
    // 通过axios发起ajax请求
    let promise = axios({
      url: BASE_URL + url,
      method: method,
      data: param,
      headers: {
        Authorization: LocalToken.load(),
      },
    });

    // 处理结果
    promise
      .then((resp) => {
        LocalToken.save(resp.data);
        cb(resp.data);
      })
      .catch((err) => {
        console.error(err);
        cb({
          code: 500,
          message: '网站忙，请稍后重试',
          success: false,
        });
      });
  },
  get: (url, param, cb) => {
    return Api.ajax(url, param, cb, 'get');
  },
  post: (url, param, cb) => {
    return Api.ajax(url, param, cb, 'post');
  },
  put: (url, param, cb) => {
    return Api.ajax(url, param, cb, 'put');
  },
  delete: (url, param, cb) => {
    return Api.ajax(url, param, cb, 'delete');
  },
  patch: (url, param, cb) => {
    return Api.ajax(url, param, cb, 'patch');
  },
};

export { BASE_URL as BASE_URL, LocalToken as LocalToken, Api as Api };
